<template>
  <el-form ref="form" label-width="80px">
    <el-form-item label="SPU名称">
      <el-input v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
        <el-option v-for="tm in tmList" :key="tm.id" :value="tm.id" :label="tm.tmName" />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" rows="4" placeholder="SPU描述" v-model="spuInfo.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload v-model:file-list="spuImageList as UploadUserFile[]" :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-select placeholder="请选择" v-model="tempSaleAttr">
        <el-option v-for="attr in unUsedSaleAttrList" :key="attr.id" :value="`${attr.id}:${attr.name}`"
          :label="attr.name" />
      </el-select>
      <el-button type="primary" size="default" @click="addSaleAttr" icon="ele-Plus" :disabled="!tempSaleAttr">添加销售属性
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-table :data="spuSaleAttrList" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{row}">
            <el-tag v-for="(tag,index) in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
              :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index,1)">
              <!-- @close="handleClose(tag)" -->
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input v-if="row.isEdit" class="ml-1 w-20" size="small" ref="editEle" v-model="row.inputValue"
              @blur="handleInputConfirm(row)" />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="changeToEdit(row)">
              + 新增属性值
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-button type="danger" size="default" icon="ele-Delete" @click="spuSaleAttrList.splice($index,1)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="default" size="default" @click="emit('setState', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import { requestBaseSaleAttrList, requestSaveSpuInfo, requestSpuImgList, requestSpuSaleAttrList, requestUpdateSpuInfo, type BaseSaleAttrListType, type SpuImgListType, type SpuInfoType, type SpuSaleAttrItemType, type SpuSaleAttrListType } from '@/api/spu';
import { requestAllTmList, type requestAllTmListReturnType } from '@/api/Trademark';
const baseUrl = import.meta.env.VITE_API_URL
// 接收props传值
const props = defineProps<{
  spuInfo: SpuInfoType
}>()

// 自定义事件传值切换组件
const emit = defineEmits<{
  ($event: "setState",
    state: number,
    row?: SpuInfoType
  ): void
}>()

// const fileList = ref<UploadUserFile[]>([
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
// ])



const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 根据当前是新增还是修改去发请求(新增需要发两个请求:1.所有品牌列表.2.所有销售属性列表..修改需要发送4个请求:1.所有品牌列表.2.所有销售属性列表.3.当前sku图片列表.4.当前sku属性列表)

// 声明一些响数据保存所有品牌列表,所有销售属性列表,当前sku图片列表,当前sku属性列表

const tmList = ref<requestAllTmListReturnType[]>([])
const saleAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImgListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])



const getAllUserData = async () => {
  // 判断当前是新增还是修改
  if (!props.spuInfo.id) {
    // 没有id说明是新增
    try {
      const result1 = await requestAllTmList()
      tmList.value = result1
      const result2 = await requestBaseSaleAttrList()
      saleAttrList.value = result2
    } catch (e) {
      ElMessage.error("品牌请求或者属性列表请求失败")
    }
  } else {
    // 有id说明是编辑
    const promise1 = requestAllTmList()
    const promise2 = requestBaseSaleAttrList()
    const promise3 = requestSpuImgList(props.spuInfo.id)
    const promise4 = requestSpuSaleAttrList(props.spuInfo.id)

    try {
      const result = await Promise.all([promise1, promise2, promise3, promise4])
      tmList.value = result[0]
      saleAttrList.value = result[1]
      spuImageList.value = result[2]
      // 处理照片墙数据
      spuImageList.value.forEach(item => {
        item.name = item.imgName
        item.url = item.imgUrl
      })
      spuSaleAttrList.value = result[3]
      // 给spu销售属性列表的每一项添加一个isEdit属性代表是否是编辑模式
      spuSaleAttrList.value.forEach(item => {
        item.isEdit = false
        //保存当前销售属性列表中 在编辑模式下输入的内容
        item.inputValue = ''
      })
    } catch (e) {
      ElMessage.error("初始请求失败")
    }
  }
}
onMounted(() => {
  getAllUserData()
})

const unUsedSaleAttrList = computed(() => {
  // 处理数据,删除当前spu已经有的销售属性
  return saleAttrList.value = saleAttrList.value.filter(item1 => {
    return spuSaleAttrList.value.every(item2 => {
      return item1.name !== item2.saleAttrName
    })
  })
})

// 声明一个数据收集用户保存的临时信息
const tempSaleAttr = ref('')

const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":")
  const tempSpuSaleAttr = {
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: [],
  }
  // 将数据插入到spuSaleAttrList里
  spuSaleAttrList.value.push(tempSpuSaleAttr)
  // 清空临时数据
  tempSaleAttr.value = ''
}

// 保存处在编辑模式的input元素
const editEle = ref<HTMLInputElement>()

// 切换到编辑模式的事件
const changeToEdit = (row: SpuSaleAttrItemType) => {
  // 切换模式
  row.isEdit = true
  // 自动获取焦点
  nextTick(() => {
    editEle.value?.focus()
  })
}

// 失去焦点的事件
const handleInputConfirm = (row: SpuSaleAttrItemType) => {
  // 获取当前输入的内容
  let inputValue = row.inputValue
  // 判断当前输入的内容是否为空
  if (!inputValue?.trim()) {
    ElMessage.error("添加的内容不能为空")
    row.isEdit = false
    return;
  }

  const isRepeat = row.spuSaleAttrValueList.some(item => {
    return item.saleAttrValueName === inputValue
  })

  // 判断输入的内容是否有重复
  if (isRepeat) {
    ElMessage.error("添加的内容有重复!")
    row.isEdit = false
    row.inputValue = ''
    return;
  }

  // 将值添加到row的属性值列表的数据中
  const newSaleAttrValue = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue as string,
  }

  // 给当前spu属性值列表添加新属性
  row.spuSaleAttrValueList.push(newSaleAttrValue)

  row.isEdit = false
  row.inputValue = ''
}

// 整理需要发送的数据
const save = async () => {
  //整理 spuImageList 数据
  const newSpuImageList = spuImageList.value.map((item) => {
    if (item.response) {
      return {
        imgUrl: item.response.data as string,
        imgName: item.name as string,
      };
    } else {
      return {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
      };
    }
  });
  console.log(spuImageList.value);
  // spuSaleAttrList上多了isEdit和inputValue属性,需要删除
  spuSaleAttrList.value.forEach(item => {
    delete item.isEdit;
    delete item.inputValue;
  })

  // 将整理好的这两个数据放到skuInfo上
  props.spuInfo.spuSaleAttrList = spuSaleAttrList.value
  props.spuInfo.spuImageList = newSpuImageList

  // 提交数据
  try {
    // 判断有没有id
    if (props.spuInfo.id) {
      // 有id说明为更新
      await requestUpdateSpuInfo(props.spuInfo)
    } else {
      // 没有说明为新增
      await requestSaveSpuInfo(props.spuInfo)
    }
  } catch (e) {
    ElMessage.error("新增或更新操作失败")
  }
  //回到列表页
  emit("setState", 0);
}
</script>